package com.example.springboottools.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.objectdet20191230.Client;
import com.aliyun.objectdet20191230.models.DetectWhiteBaseImageAdvanceRequest;
import com.aliyun.objectdet20191230.models.DetectWhiteBaseImageResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

public class AliYunImage {



    public static void main(String[] args) {
        try {
            //String imgUrl= "http://newvp-pic.staplescn.com/static_adv/ftp_product_img//cn7700983228EA_1_xnl.jpg";
            //String imgUrl= "http://newvp-pic.staplescn.com/static_adv/ftp_product_img//cn1101358908EA_1_xnl.jpg";
           // String imgUrl= "https://newvp-pic.staplescn.com/static_adv/ftp_product_img//cn7701087167EA_1_xnl.jpg";
            //URL url = new URL(imgUrl);
           // BufferedImage read = ImageIO.read(url);
            File file = new File("C:\\Users\\SH102909\\Downloads\\cn7701087167EA_1_xnl (1).jpg");
            BufferedImage read = ImageIO.read(file);
            System.out.println(read);
            if (read == null)return;
            System.out.println("图片宽高："+read.getWidth()+"---"+read.getHeight());
            /*InputStream inputStream = url.openConnection().getInputStream();
            String accessKeyId = "LTAI4FykcchFoy1oGMA9Q32d";
            String accessKeySecret = "NbgDJ9syKIJVmjEkJ6ClrDVN4F3OQE";
            RuntimeOptions runtime = new RuntimeOptions();

            // 用户账号配置
            Config config = new Config().setAccessKeyId(accessKeyId).setAccessKeySecret(accessKeySecret);
            config.endpoint = "objectdet.cn-shanghai.aliyuncs.com"; // 访问的域名
            Client client = new Client(config);
            DetectWhiteBaseImageAdvanceRequest imageAdvanceRequest = new DetectWhiteBaseImageAdvanceRequest().setImageURLObject(inputStream);
            DetectWhiteBaseImageResponse imageResponse = client.detectWhiteBaseImageAdvance(imageAdvanceRequest, runtime);
            System.out.println("返回结果："+ JSON.toJSONString(imageResponse));*/
            // 推送路径
//            String serverUrl = "http://rgw.staplescn.com/" + "api/" + "staticadv";
//            // token
//            String token = "Token 4de60056aeff5de46a318493e79bf024a6dbe657";
//            // 上传目录
//            Map<String,String> params = new HashMap<>();
//            params.put("filepath", "ftp_product_img/");
//            String file = "D:\\cn7701087167EA_1_xnl.jpg";//本地图片地址
//            //String fileName = "cn7701087167EA_1_xnl.jpg";//文件名称，可为空
//            Map<String, Object> map = uploadLocalFile(serverUrl, token, file, null, params);
//            System.out.println(map);


        }catch (Exception e){
            System.out.println("异常："+ JSON.toJSONString(e));
        }

    }

    static String BOUNDARY = "" + System.currentTimeMillis();// 设置分隔符
    /**
     * 上传本地文件
     * @param serverUrl URL地址
     * @param file 本地文件地址
     * @param fileName 文件名
     * @param params 参数
     * @param token token认证
     * @return 服务器返回结果
     * @throws Exception
     *
     */
    public static Map<String,Object> uploadLocalFile(String serverUrl, String token, String file, String fileName, Map<String, String> params) {

        // 目前不允许批量上传文件
        // 因为其中一份文件传输失败，后续处理会很麻烦
        String[] filePaths = {file};
        String [] fileNames = fileName != null ? new String[]{fileName} : null;
        Map<String,Object> resultMap = new HashMap<>();

        try{
            // 向服务器发送post请求
            URL url = new URL(serverUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置传输形式
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            // 添加请求头
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            if (StringUtils.isNotBlank(token)) connection.setRequestProperty("Authorization",token);

            // 链接服务器获得输出流
            OutputStream out = new DataOutputStream(connection.getOutputStream());
            StringBuilder message = new StringBuilder();//存放请求信息

            // 第一部分：传输参数
            for (String key : params.keySet()) {
                message.append("--").append(BOUNDARY).append("\r\n").append("Content-Disposition: form-data; name=\"")
                        .append(key + "\"").append("\r\n").append("\r\n").append(params.get(key)).append("\r\n");
            }
            String boundaryMessage1 = message.toString();
            out.write(boundaryMessage1.getBytes("utf-8"));

            // 第二部分： 传输文件
            for (int i = 0; i < filePaths.length; i++) {
                File f = new File(filePaths[i]);
                String fname = fileNames == null ? f.getName() : fileNames[i];

                if (!f.exists()) {
                    throw new Exception("文件不存在或路径错误!");
                }
                message.delete(0, message.length());
                message.append("--");
                message.append(BOUNDARY);
                message.append("\r\n");
                message.append("Content-Disposition: form-data;name=\"filename\";filename=\"" + fname + "\"\r\n");
                message.append("Content-Type:application/octet-stream\r\n\r\n");
                byte[] head = message.toString().getBytes("utf-8");

                // 输出文件表头
                out.write(head);
                // 文件正文部分
                // 把文件已流文件的方式 推入到url中
                DataInputStream in = new DataInputStream(new FileInputStream(f));
                int bytes = 0;
                byte[] bufferOut = new byte[1024];
                while ((bytes = in.read(bufferOut)) != -1) {
                    out.write(bufferOut, 0, bytes);
                }

                // 写入两个文件之间得分隔符，如果没有两个文件内容会被写在一个文件中
                out.write("\r\n".getBytes("utf-8"));
            }
            // 结尾部分
            byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
            out.write(foot);
            out.flush();

            // 4. 从服务器获得回答的内容
            String strLine = "";
            String result = "";
            InputStream responseIO = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(responseIO));
            while ((strLine = reader.readLine()) != null) {
                result += strLine + "\n";
            }
            if(StringUtils.isBlank(result)) {
                throw new RuntimeException("请求返回空值异常！");
            }

            // 5.unicode编码转中文，示例：[{"file_name": "test_lyx/\u9501.jpg", "file_size": 29250, "status": "SUCCESS"}]
            result = anUnicode(result);
            System.out.println("##### 文件存储系统【ADD】返回结果：" + result);

            // 6.解析返回结果 LIST&MAP
            if(result.indexOf("[") != -1){
                resultMap = (Map<String, Object>) JSONArray.parseArray(result).get(0);
            }else{
                resultMap = (Map<String, Object>) JSONObject.parse(result);
            }

        }catch (Exception e){
            String method = Thread.currentThread().getStackTrace()[1].getMethodName(); // 方法名
           // logger.error( method + "方法，调用【文件存储系统】异常：",e);
            resultMap.put("status","FAILED");
            resultMap.put("msg",e.getMessage());
        }
        // 操作失败，输出参数
        if(!"SUCCESS".equals(resultMap.get("status"))){
          //  logger.error("【文件存储系统】请求失败参数：" + serverUrl + "，" + file + "，" + fileName + "，" + params);
            // 两种错误返回形式：{"detail":"认证令牌无效。"}、{"status":"FAILED","res_code":90001,"msg":"请求参数异常"}
           // String msg = Helper.toString(resultMap.get("msg")) + Helper.toString(resultMap.get("detail"));
            resultMap.put("msg",DateUtils.getCurrentDate(null) + "：" + ("msg"));
        }
        return resultMap;
    }

    /***
     * unicode编码转中文
     * @param unicode
     * @return
     */
    private static String anUnicode(String unicode) {
        if (StringUtils.isBlank(unicode)) {
            return unicode;
        }

        final int len = unicode.length();
        StringBuilder sb = new StringBuilder(len);
        int i = -1;
        int pos = 0;
        while ((i = StringUtils.indexOfIgnoreCase(unicode, "\\u", pos)) != -1) {
            sb.append(unicode, pos, i);//写入Unicode符之前的部分
            pos  = i;
            if (i + 5 < len) {
                char c = 0;
                try {
                    c = (char) Integer.parseInt(unicode.substring(i + 2, i + 6), 16);
                    sb.append(c);
                    pos = i + 6;//跳过整个Unicode符
                } catch (NumberFormatException e) {
                    //非法Unicode符，跳过
                    sb.append(unicode, pos, i+2);//写入"\\u"
                    pos = i + 2;
                }
            }else {
                pos = i;//非Unicode符，结束
                break;
            }
        }

        if(pos < len) {
            sb.append(unicode,pos, len);
        }
        return sb.toString();
    }
}
